//import Pagination from 'ant-design-vue/lib/Pagination';
//import 'ant-design-vue/lib/pagination/style';
import { defineComponent, reactive, toRefs } from 'vue';
import Http from '../../service/Http';

interface Props {
    queryParams : {[key : string] : any};
    load: {(queryParams : any) : any};
    [key : string] : any;
    
}

export default defineComponent({
    props : {
        url : {
            type : String,
            default : ''
        },

        load : {
            type : Function,
            default() {
                return function(){}
            }
        },

        queryParams : {
            type : Object,
            default() {
                return {}
            }
        },

        showSizeChanger: {
            type : Boolean,
            default() {
                return true
            }
        }
    },

    setup(props : any, context) {
        let state = reactive({
            total : 0,
            pageSize : 10,
            pageNo : 1,
            loading : false
        })

        let http = new Http()


        function sizeChange(pageNo, pageSize) {
            state.pageNo = pageNo
            state.pageSize = pageSize

            pagination(pageNo)
        }

        async function pagination(pageNo = 1) {
            if(state.loading) return

            let queryParams = {...props.queryParams}
            queryParams.startPage = pageNo
			queryParams.pageNo = pageNo
			queryParams.pageSize = state.pageSize

            state.loading = true
            state.pageNo = pageNo

            let res = await props.load(queryParams)

            state.loading = false

            try{
                let data = res.data
                if(res.success && data) {
                    state.total = data.pageCount || 0
                    var pageData = data.pageData || []
                    pageData.forEach(row => {
                        row.$loading = false
                    })
                    context.emit('finish', pageData)
                }else {
                    context.emit('finish', [])
                }
                
            }catch(e){}
        }


        pagination(1)

        return {
            ...toRefs(state),
            pagination,
            sizeChange,

        }
    },

    render() {
        const { showSizeChanger, loading, pageNo, pageSize, sizeChange, pagination, total} = this
        return <div style='display:inline-flex;align-items:center;'>
        {loading &&
            <a-spin style='margin-right:10px' />
        }
        <a-pagination showSizeChanger={showSizeChanger} disabled={loading} current={pageNo} pageSize={pageSize} total={total} onShowSizeChange={sizeChange} onChange={pageNo => { pagination(pageNo) }} />
        </div>
    }
})